package com.ltt.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * @author ‘李天泰’
 * @version 1.0
 * @description: JWT认证的工具类
 * @date 2023/4/30 17:07
 */
public class JWTUtils {
    public static final String AUTH_HEADER_KEY = "Authorization";

    public static final String TOKEN_PREFIX = "Bearer";

    // 过期时间为一周
    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;

    private static final String secret = "5rSL5q+b5Ye66Ieq5rSL6Lqr5LiK";

    public static void main(String[] args) {
        Long id = 15464512L;
        String sign = sign(id);
        System.out.println(sign);
        System.out.println(verify(sign));
        System.out.println(getUserId(sign));
        System.out.println(isExpire(sign));
    }

    /**
     * @param id
     * @return java.lang.String
     * @description: 生成token，设置id属性
     */
    public static String sign(Long id) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            // 附带username信息
            return JWT.create()
                    .withClaim("id", id)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    /**
     * @param token
     * @return boolean
     * @description: 检验token密钥是否正确
     */
    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * @param token
     * @return java.lang.Long token中包含的id
     * @description: 获取token中的信息无需secret解密也能获得
     */
    public static Long getUserId(String token) {
        try {
            DecodedJWT decode = JWT.decode(token);
            return decode.getClaim("id").asLong();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * @description: 判断是否过期
     * @param token
     * @return boolean
     */
    public static boolean isExpire(String token) {
        DecodedJWT decode = JWT.decode(token);
        return System.currentTimeMillis() > decode.getExpiresAt().getTime();
    }
}
